<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use PragmaRX\Google2FALaravel\Facade as Google2FA;

class Google2faController extends Controller
{

    public function index(Request $request)
    {
        if ($request->session()->has('users')) {
            return redirect()->route('admin');
        }

        // 获取数据库 Secret
        $google2faSecret = $request->user()->google2fa_secret;

        // 如果不存在，则初始化 Secret
        if (empty($google2faSecret)) {
            $google2fa = app('pragmarx.google2fa');

            // 获取 Secret
            $google2faSecret = $google2fa->generateSecretKey();

            // 获取二维码
            $qrCode = Google2FA::getQRCodeInline(
                config('app.name') . '.' . config('app.env'),
                $request->user()->email,
                $google2faSecret
            );

            // Session 缓存 Secret
            $request->session()->put('google2fa_cache', $google2faSecret);
        }

        return view('auth.passwords.google2fa', [
            'qrCode' => $qrCode ?? null
        ]);
    }

    public function verify(Request $request)
    {
        $user = $request->user();

        // 获取 Secret
        $google2faSecret = $request->session()->get('google2fa_cache', function () use ($user) {
            // 获取数据库 Secret
            return $user->google2fa_secret;
        });

        // Secret 不存在
        if (empty($google2faSecret)) {
            return redirect()->route('g2fa.request');
        }

        $this->validate($request, [
            'g2fa_code' => ['required', 'string', 'size:6',
                function ($attribute, $code, $fail) use ($google2faSecret) {
                    $google2fa = app('pragmarx.google2fa');
                    // 校验验证码
                    if (!$google2fa->verifyKey($google2faSecret, $code)) {
                        $fail(trans('validation.google2fa'));
                    }
                }
            ],
        ]);

        // 保存 Secret
        if (empty($user->google2fa_secret)) {
            $user->google2fa_secret = $google2faSecret;
            $user->save();
        }

        // Session 标记已通过验证
        $request->session()->put('google2fa', true);
        // 清除 Session 缓存 Secret
        $request->session()->forget('google2fa_cache');

        return redirect()->route('admin');
    }
}
